<template>
  <div>
    <!-- 页面头 -->
    <header class="header">
      <div class="header_left">
        <span @click="goBack">
          <i class="mintui mintui-back"></i>返回</span>
      </div>
      <div class="header_right">
        <span @click="goBack">取消</span>
      </div>
    </header>
    <div class="video">
      <video-player :isAudio="isAudio" v-if="playAble" @error="onPlayerError($event)" @pause="onPlayerPause($event)" @play="onPlayerPlay($event)" @ended="onPlayerEnded($event)" @timeupdate="onPlayerTimeupdate($event)" class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="playsinline" :options="playerOptions">

      </video-player>
      <view v-else>
        开始考试
      </view>
    </div>
    <div v-if="introOpen" :style="{height:contentHeight}" class="intro">
      <div class="title">{{lesson.title}}</div>
      <p class="content" v-html="lesson.content"></p>
    </div>
    <div v-else class="question-and-answer">
      <div class="title">答疑</div>
      <div class="line"></div>
      <div class="time">{{new Date()|dateformat('HH:mm')}}</div>
      <div class="listPage">
        <mt-loadmore ref="loadMore" :auto-fill="false" :top-method="loadTop" @bottom-status-change="handleBottomChange" :bottom-all-loaded="allLoaded">
          <div style="min-height:200px">
            <div v-for="(item,index) in this.myAnswerList.list" :key="index">
              <div v-if="item.flag=='question'" class="question">
                <span class="content">
                  {{item.content}}
                </span>
                <span class="img"><img :src="personIcon" /></span>
              </div>
              <div v-if="item.flag=='answer'" class="answer">
                <span class="img"><img :src="personIcon" /></span>
                <span class="content">
                  {{item.content}}
                </span>
              </div>
            </div>
          </div>
        </mt-loadmore>
      </div>
      <div class="inputgroup">
        <input v-model="questionInput">
        <mt-button type="primary" @click="send" size="small">发送</mt-button>
      </div>
    </div>
    <div>
      <section id="foot_nav">
        <section @click="getMenu" class="foot_item">
          <img class="icon_style" :src="menu" /> 目录
        </section>
        <section @click="audioPlay" class="foot_item">
          <img class="icon_style" :src="audio" /> 音频
        </section>

        <section @click="videoPlay" class="foot_item">
          <img class="icon_style" :src="video" /> 视频
        </section>

        <section @click="getQuestion" class="foot_item">
          <img class="icon_style" :src="question" /> 答疑
        </section>
        <!-- <section @click="shareToOther" class="foot_item">
          <img class="icon_style" :src="share" /> 分享
        </section> -->
      </section>
    </div>
    <exam-dialog ref="examDialog" v-bind="examDialogConfig" v-on:confirm="next" v-on:cancle="last">
      <div v-if="questionList[0]" slot="content" class="content">
        <div class="content">
          {{questionNo+1}}. {{questionList[questionNo].content}}
        </div>
        <div class="item no-mint-style">
          <mt-radio class="selection-list" v-model="answer[questionList[questionNo].questionid]" :options="questionInfo.items"></mt-radio>
        </div>
      </div>
    </exam-dialog>
    <my-dialog ref="myDialog" v-bind="dialogConfig" v-on:cancle="cancleExam" v-on:confirm="startExam"></my-dialog>
    <!-- <mt-popup v-model="popupVisible" position="bottom" class="mint-popup">
      <div class="share-item">
        <img :src="wechat" />
      </div>
      <div class="share-item">
        <img :src="wechatCircle" />
      </div>
      <div class="share-item">
        <img :src="qq" />
      </div>
      <div class="share-item">
        <img :src="qqSpace" />
      </div>
      <div class="share-item">
        <img :src="weibo" />
      </div>
    </mt-popup> -->
  </div>
</template>

<script type="text/ecmascript-6">
import api from '@/api/index'
import userApi from '@/api/user'
import testApi from '@/api/test'
import utils from '@/utils'
import Dialog from '@/components/dialog'
import { MessageBox, Toast } from 'mint-ui'
import audio from '@/assets/images/课程学习_音频.png'
import video from '@/assets/images/课程学习_视频.png'
import study from '@/assets/images/课程学习_线下学习.png'
import share from '@/assets/images/课程学习_分享.png'
import menu from '@/assets/images/课程学习_菜单.png'
import menuActive from '@/assets/images/课程学习_菜单_选中.png'
import personIcon from '@/assets/images/personal/个人中心_完善资料_头像.png'
import audioAcitve from '@/assets/images/课程学习_音频_选中.png'
import videoAcitve from '@/assets/images/课程学习_视频_选中.png'
import studyAcitve from '@/assets/images/课程学习_线下学习_选中.png'
import shareAcitve from '@/assets/images/课程学习_分享_选中.png'
import questionAcitve from '@/assets/images/课程学习_答疑_选中.png'
import question from '@/assets/images/课程学习_答疑.png'
import pass from '@/assets/images/测验通过.png'
import noPass from '@/assets/images/测验不通过.png'
import personHead from '@//assets/images/底_个人中心_b.png'
import audioJpg from '@/assets/images/audio.jpg'
import audioGif from '@/assets/images/audio.gif'
import wechat from '@/assets/images/wechat.gif'
import wechatCircle from '@/assets/images/wechatCircle.gif'
import qq from '@/assets/images/qq.gif'
import qqSpace from '@/assets/images/qqSpace.gif'
import weibo from '@/assets/images/weibo.gif'
export default {
  data () {
    return {
      contentHeight: '',
      allLoaded: false,
      myAnswerList: { pageNo: 0, pageSize: 10, list: [] },
      userId: '',
      myHeadImg: '',
      questionInput: '',
      row: 3,
      introOpen: true,
      popupVisible: false,
      isAudio: false,
      playsinline: true,
      playAble: false,
      activeButton: 'video',
      // examStarted: false,
      currentTime: 0,
      playBacktime: 0,
      finish: false,
      lessonid: '',
      lesson: {},
      logined: false,
      questionList: [],
      questionInfo: {},
      answer: {},
      playerOptions: {
        playbackRates: [], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'true', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: '',
            src: '' // 你的视频地址（必填）
          }
        ],
        poster: '', // 你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此课程暂无法视频', // 许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true // 全屏按钮
        }
      },
      questionNo: 0,
      dialogConfig: {
        content: '课程学习完毕,确定要立刻开始章节测试吗?',
        closable: false
      }
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.contentHeight = window.innerHeight - 320 + 'px'
      console.log(this.contentHeight)
    })
  },
  created () {
    this.initPage()
  },
  computed: {
    menu: function () {
      return this.activeButton === 'menu' ? menuActive : menu
    },
    audio: function () {
      return this.activeButton === 'audio' ? audioAcitve : audio
    },
    video: function () {
      return this.activeButton === 'video' ? videoAcitve : video
    },
    study: function () {
      return this.activeButton === 'study' ? studyAcitve : study
    },
    share: function () {
      return this.activeButton === 'share' ? shareAcitve : share
    },
    question: function () {
      return this.activeButton === 'question' ? questionAcitve : question
    },
    sysPersonHead: function () {
      return personHead
    },
    examDialogConfig: function () {
      var config = {
        title: '随堂测验',
        closable: false
      }
      config.subhead = '第' + (this.questionNo - 0 + 1) + '题/共3题'
      config.confirm = this.hasNext() ? '下一题' : '交卷'
      config.cancel = this.hasLast() ? '上一题' : '退出测试'
      return config
    },
    wechat () {
      return wechat
    },
    wechatCircle () {
      return wechatCircle
    },
    qq () {
      return qq
    },
    qqSpace () {
      return qqSpace
    },
    weibo () {
      return weibo
    },
    personIcon () {
      return personIcon
    },
    intro () {
      var value = this.lesson.content
      if (value) {
        value = '　　' + value
      }
      return value
    }
  },

  components: {
    myDialog: Dialog,
    examDialog: Dialog
  },

  methods: {
    onDateChange (picker, values) {
      if (values[0] > values[1]) {
        picker.setSlotValue(1, values[0])
      }
      this.dateStart = values[0]
      this.dateEnd = values[1]
    },
    next () {
      if (this.hasNext()) {
        console.log(this.questionInfo)
        this.questionNo = this.questionNo + 1
        this.questionInfo = this.questionList[this.questionNo]
        console.log('当前的答案数据', this.answer)
        console.log(this.questionInfo)
      } else {
        // 中途退出就是交白卷
        this.submit()
      }
    },
    hasNext () {
      if (this.questionNo < 2 && this.questionNo < this.questionList.length - 1 && !utils.isEmptyObject(this.questionList[this.questionNo + 1])) {
        return true
      } else {
        return false
      }
    },
    last () {
      if (this.hasLast()) {
        this.questionNo = this.questionNo - 1
        this.questionInfo = this.questionList[this.questionNo]
        console.log('当前的答案数据', this.answer)
      } else {
        this.routerBack()
      }
    },
    hasLast () {
      if (this.questionNo > 0) {
        return true
      } else {
        return false
      }
    },
    submit () {
      let answer = {}
      var count = 0
      for (let i in this.answer) {
        if (this.answer[i]) {
          answer[i] = this.answer[i] - 0
          count++
        }
      }
      console.log('当前答案的长度为', this.answer.length)
      console.log(answer)
      if (count < this.questionList.length) {
        MessageBox.alert('存在尚未完成的题目,请继续考试', '确定')
      } else {
        this.$refs.examDialog.close()
        testApi.finishExam({
          params: {
            lessonid: this.lessonid,
            answermap: JSON.stringify(answer)
          }
        }).then(resp => {
          let throughMessage = '<div><div style="font-size: 18px;color: #1f88fe;text-align: center;line-height: 36px;height: 36px;">随堂测验</div><div style="width: 100%;height: 1px;background-color: #e0e0e0;"></div><img src="' + pass + '" height="100px" width:"100px" style="margin-top:20px"/><div>测试通过</div></div>'
          let noPassMessage = '<div><div style="font-size: 18px;color: #1f88fe;text-align: center;line-height: 36px;height: 36px;">随堂测验</div><div style="width: 100%;height: 1px;background-color: #e0e0e0;"></div><img src="' + noPass + '" height="100px" width:"100px" style="margin-top:20px"/><div>测试不通过</div></div>'
          MessageBox({
            title: '',
            message: resp.result.pass ? throughMessage : noPassMessage,
            confirmButtonText: resp.result.pass ? '返回' : (resp.result.retrytime >= 3 ? '重新学习' : '再次考试'),
            confirmButtonClass: 'button'
          }).then(action => {
            if (resp.result.pass) {
              this.routerBack()
            } else {
              this.initPage()
            }
          })
        }).catch(resp => {
          Toast(resp.message)
        })
      }
    },
    getPlayBacktime () {
      api.getPlayBacktime({
        params: {
          lessonid: this.lessonid
        }
      }).then(resp => {
        this.currentTime = resp.result.playbacktime / 1000
      })
    },
    initPage () {
      this.lessonid = this.$route.query.lessonid
      this.logined = utils.checkUserLogined()
      this.questionList = []
      this.answer = []
      this.questionNo = 0
      // 获取章节详情并渲染
      api.getLesson({
        params: {
          lessonid: this.lessonid
        }
      }).then(resp => {
        this.lesson = resp.result
        if (this.lesson) {
          if (this.lesson.stage === 'CONTINUE') {
            console.log('CONTINUE')
            this.getPlayBacktime()
          } else if (this.lesson.stage === 'EXAMINATION') {
            console.log('EXAMINATION')
            this.finish = true
            this.playAble = false
            this.startExam()
          } else if (this.lesson.stage === 'DISABLED') {
            console.log('DISABLED')
            this.routerBack()
          }
        }
        this.videoPlay()
        this.playAble = true
      })
      userApi.getUserInfo().then(resp => {
        this.myHeadImg = resp.result.avatarurl || this.sysPersonHead
        this.userId = resp.result.userid || ''
        this.myAnswerList = { pageNo: 0, pageSize: 10, list: [] }
        this.getMyAnswerList()
      })
    },
    goBack () {
      this.routerBack()
    },
    routerBack () {
      this.$router.push({ path: '/index/courseInfo', query: { courseid: this.$route.query.courseid } })
    },
    // 同步播放时间
    modifyPlayBacktime (afterModify) {
      console.log('同步播放时间', this.currentTime)
      api.modifyPlayBacktime({
        params: {
          lessonid: this.lessonid,
          playbacktime: Math.round(this.playBacktime * 1000),
          finish: this.finish
        },
        headers: {
          NLoading: '1'
        }
      })
    },
    startExam () {
      this.getQuestionList()
    },
    cancleExam () {
      this.$refs.examDialog.close()
      this.routerBack()
    },
    getQuestionList () {
      this.$refs.myDialog.close()
      testApi.startExam({
        params: {
          lessonid: this.lessonid
        }
      }).then(resp => {
        const result = resp.result || []
        let questionList = []
        for (let i = 0; i < result.length; i++) {
          let items = []
          let r = result[i]
          if (utils.isEmptyObject(r)) {
            continue
          }
          if (r.optiona) {
            items.push({
              value: '1',
              label: r.optiona
            })
          }

          if (r.optionb) {
            items.push({
              value: '2',
              label: r.optionb
            })
          }

          if (r.optionc) {
            items.push({
              value: '3',
              label: r.optionc
            })
          }

          if (r.optiond) {
            items.push({
              value: '4',
              label: r.optiond
            })
          }

          questionList.push({
            index: i,
            questionid: r.questionid,
            content: r.content,
            questiontype: r.questiontype,
            items: items
          })
        }
        this.questionList = questionList
        this.questionInfo = this.questionList[0]
        this.$refs.examDialog.open()
      }).catch(resp => {
        Toast(resp.message)
      })
    },
    getMenu () {
      this.activeButton = 'menu'
      console.log('try show the menu page')
      this.$router.push({ path: '/index/menuPage', query: { courseid: this.$route.query.courseid, lessonid: this.$route.query.lessonid } })
    },
    getQuestion () {
      if (this.logined) {
        console.log('try show the question page')
        this.activeButton = 'question'
        this.introOpen = false
        this.playAble = false
      } else {
        MessageBox.confirm('您还没有登录,现在要登录吗?').then(action => {
          this.$router.push({ path: '/login' })
        })
      }
    },
    studyOutLine () {
      this.activeButton = 'study'
      alert('模块开发中...')
    },
    shareToOther () {
      this.activeButton = 'share'
      this.popupVisible = true
    },
    audioPlay () {
      this.activeButton = 'audio'
      this.introOpen = true
      console.log('尝试播放音频')
      this.playerOptions.sources[0].src = this.lesson.audiourl
      this.playerOptions.notSupportedMessage = '该课程暂无音频'
      this.playerOptions.poster = audioJpg
      this.isAudio = true
      this.playAble = true
    },
    videoPlay () {
      console.log('尝试播放视频')
      this.introOpen = true
      this.playerOptions.notSupportedMessage = '该课程暂无视频'
      this.activeButton = 'video'
      this.playerOptions.poster = ''
      this.playerOptions.sources[0].src = this.lesson.videourl
      this.isAudio = false
      this.playAble = true
    },
    onPlayerPlay (player) {
      if (this.lesson.stage === 'EXAMINATION') {
        player.pause()
        this.finish = true
        this.startExam()
      } else if (this.lesson.stage === 'DISABLED') {
        player.pause()
        this.routerBack()
      }
      console.log('这是要从哪里开始播放呢?', this.currentTime)
      player.currentTime(this.currentTime)
    },
    onPlayerPause (player) {
      // if (this.isAudio) {
      //   this.playerOptions.poster = audioJpg
      // }
    },
    onPlayerEnded (player) {
      if (this.logined) {
        if (this.lesson.stage === 'CONTINUE') {
          this.finish = true
          this.modifyPlayBacktime()
          this.playAble = false
          this.$refs.myDialog.open()
        }
      }
    },
    onPlayerError (player) {
      console.log('播放失败了')
      this.playerOptions.notSupportedMessage = '媒体资源不存在或无法解析'
      this.playerOptions.sources[0].src = ''
    },
    onPlayerTimeupdate (player) {
      let playTime = player.currentTime()
      console.log('当前的播放时间获取异常', playTime)
      if (this.logined) {
        if (this.lesson.stage === 'CONTINUE') {
          if (playTime - this.currentTime > 5 || playTime - this.currentTime < -10) {
            // console.log('回调黑洞', this.currentTime)
            // console.log('当前记录的播放时间为', this.currentTime)
            // console.log('当前视频的播放时间为', playTime)
            player.currentTime(this.currentTime)
          } else {
            console.log('播放时间更新了', this.currentTime, playTime)
            this.currentTime = playTime
            if (this.currentTime - 0 - this.playBacktime > 11) {
              this.playBacktime = this.currentTime
              this.modifyPlayBacktime()
            }
          }
        } else if (this.lesson.stage === 'FREE') {
          this.currentTime = player.currentTime()
        }
      } else {
        this.currentTime = player.currentTime()
      }
    },
    send () {
      api.addMyQuestion({
        params: {
          content: this.questionInput
        }
      }).then(resp => {
        // Toast('提交成功,请等待管理员审核')
        this.getMyAnswerList()
        this.questionInput = ''
      }).catch(resp => {
        Toast(resp.message)
      })
    },
    getMyAnswerList () {
      api.getMyAnswerList({
        params: {
          pageno: this.myAnswerList.pageNo,
          pagesize: this.myAnswerList.pageSize
        }
      }).then(resp => {
        var list = resp.result
        if (list || list.length > 0) {
          for (let i in list) {
            if (list[i].senderid === this.userId) {
              list[i].flag = 'question'
            } else {
              list[i].flag = 'answer'
            }
          }
          if (this.myAnswerList.list.length % 10 !== 0) {
            this.allLoaded = true
            this.myAnswerList.list = list.reverse()
            console.log('需要渲染的数据为', this.myAnswerList.list)
          } else {
            this.myAnswerList.list = list.reverse()
          }
        }
      })
    },
    loadTop () {
      this.myAnswerList.pageSize += 10
      this.getMyAnswerList()
      this.$refs.loadMore.onTopLoaded()
    },
    handleBottomChange () {

    }
  }
}
</script>

<style lang="scss" scoped>
$scale: 1px;
$font-scale: 1.2;
.header {
  display: flex;
  justify-content: space-between;
  padding-left: 16px;
  padding-right: 16px;
  padding-top: 16px;
  height: 55px;

  .header_left {
    span {
      font-size: 18px;
      color: #1f88fe;
    }
  }

  .header_right {
    span {
      font-size: 18px;
      color: #1f88fe;
    }
  }
}
.intro {
  margin-left: 20px;
  margin-right: 20px;
  overflow: scroll;
  .title {
    line-height: 50px;
    height: 50px;
    font-size: 17px * $font-scale;
    color: #333333;
    text-align: left;
  }
  .content {
    font-size: 12px * $font-scale;
    color: #333333;
    text-align: left;
    line-height: 20px;
  }
}
p {
  text-indent: 2em;
}
#foot_nav {
  background-color: #fff;
  position: fixed;
  z-index: 100;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  box-shadow: 0 -0.026667rem 0.053333rem rgba(0, 0, 0, 0.1);
  padding-top: 9px;
  padding-bottom: 3px;
}
.foot_item {
  flex: 1;
  color: #1f1f1f;
  line-height: 24px;
  font-size: 12px * $font-scale;
  display: flex;
  text-align: center;
  flex-direction: column;
  align-items: center;
}
.icon_style {
  fill: #ccc;
  height: 24px;
  width: 24px;
}
.button {
  width: 100px;
  background-color: #1f88fe;
  font-size: 16px;
}
.message-title {
  font-size: 18px;
  color: #1f88fe;
  text-align: center;
  line-height: 36px;
  height: 36px;
}
.mint-popup {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .picker-slot-wrapper,
  .picker-item {
    backface-visibility: hidden;
  }
  .share-item {
    img {
      width: 80%;
    }
    width: 25%;
    margin-top: 5px;
    margin-bottom: 5px;
  }
}
.placehold {
  height: 100px;
}
.question-and-answer {
  .listPage {
    margin-bottom: 100px;
  }
  font-size: 14px;
  .title {
    z-index: -1;
    position: absolute;
    top: 20px;
    font-size: 18px;
    line-height: 18px;
    padding-bottom: 20px;
    color: #1f88fe;
    width: 100%;
    text-align: center;
    border-bottom: solid 1px lightgrey;
  }
  .time {
    line-height: 40px;
    font-size: 12px;
    color: lightgray;
    height: 40px;
  }
  .question {
    margin: 20px;
    display: flex;
    justify-content: flex-end;
    .content {
      padding: 10px;
      border-radius: 6px;
      text-align: right;
      background-color: #ddf5ff;
    }
    .img {
      margin-top: auto;
      margin-bottom: auto;
      margin-left: 10px;
      height: 30px;
      width: 30px;
      img {
        width: 30px;
        height: 30px;
      }
    }
  }
  .answer {
    margin: 20px;
    display: flex;
    justify-content: flex-start;
    .content {
      padding: 10px;
      border-radius: 6px;
      text-align: left;
      background-color: #ddf5ff;
    }
    .img {
      margin-top: auto;
      margin-bottom: auto;
      margin-right: 10px;
      height: 30px;
      width: 30px;
      img {
        margin: auto;
        width: 30px;
        height: 30px;
      }
    }
  }
  .inputgroup {
    background-color: #f3f3f3;
    position: fixed;
    bottom: 60px;
    width: 100%;
    padding: 10px;
    input {
      margin-right: 20px;
      padding-right: 10px;
      border-radius: 4px;
      height: 33px;
      width: 70%;
    }
  }
}
</style>
